<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     :size="size" v-if="mode === 'list'"
                     label-position="left">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="门店" prop="shopId" v-if="!shopId">
                            <el-select v-model="condition.search.shopId" placeholder="请选择门店" style="width:200px;">
                                <el-option
                                    v-for="item in shops"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                    {{ item.name }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="分类" prop="category">
                            <el-select v-model="condition.search.category"
                                       placeholder="分类">
                                <el-option
                                    v-for="item in category"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="标题" prop="title">
                            <el-input v-model="condition.search.title"
                                      placeholder="标题"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="showAddDialog">新增</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="exportExcel">导出</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     :size="size" v-if="mode === 'select'"
                     label-position="left">
                <el-row>
                    <el-col>
                        <el-form-item prop="shopId" v-if="!shopId">
                            <el-select v-model="condition.search.shopId" placeholder="请选择门店" style="width:200px;"
                                       clearable>
                                <el-option
                                    v-for="item in shops"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                    {{ item.name }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="category">
                            <el-select v-model="condition.search.category" clearable
                                       placeholder="分类">
                                <el-option
                                    v-for="item in category"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="showAddDialog">新增</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            v-if="mode === 'list'"
            id="mainTable"
            :data="tableData"
            :size="size"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="60">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="shopName"
                label="门店">
            </el-table-column>
            <el-table-column
                prop="category"
                :formatter="formatCategory"
                label="分类">
            </el-table-column>
            <el-table-column
                prop="title"
                label="标题">
            </el-table-column>
            <el-table-column
                prop="description"
                label="描述">
            </el-table-column>
            <el-table-column
                prop="url"
                width="120px"
                label="地址">
                <template v-slot="scope">
                    <media-show :url="scope.row.url" :preview-src-list="albumUrls"></media-show>
                </template>
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
            <el-table-column
                prop="createBy"
                label="谁创建的">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                prop="updateBy"
                label="谁更新的">
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                fixed="right"
                width="80px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div v-if="mode === 'select'">
            <el-row
                v-for="item in rowsData" :key="item.id">
                <el-col :span="4" v-for="col in item.cols" :key="item.id">
                    <div>
                        <el-image v-if="col.type === 'image'"
                                  style="width: 150px; height: 150px"
                                  fit="contain"
                                  :src="col.url"
                                  :preview-src-list="albumUrls">
                        </el-image>
                        <video v-else
                               style="width: 150px; height: 150px"
                               :src="col.url"
                               controls
                               class="video"
                               width="100%">
                        </video>
                        <div class="album-text">
                            <div>
                                名称：{{ col.title }}
                            </div>
                            <div>
                                大小：{{ col.size }}KB
                            </div>
                            <div>
                                <el-button type="text" size="small" @click="onSelect(col)">
                                    选择
                                </el-button>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[18, 36, 54, 72]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible" append-to-body>
            <el-form :model="addOrUpdateForm" label-width="120px" :size="size">
                <el-form-item label="选择门店" v-if="!shopId">
                    <el-select v-model="addOrUpdateForm.shopId" placeholder="请选择门店" style="width:200px;">
                        <el-option
                            v-for="item in shops"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            {{ item.name }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分类">
                    <el-select v-model="addOrUpdateForm.category" clearable
                               placeholder="分类">
                        <el-option
                            v-for="item in category"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标题">
                    <el-input v-model="addOrUpdateForm.title"
                              placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="addOrUpdateForm.description" type="textarea"
                              placeholder="描述"></el-input>
                </el-form-item>
                <el-form-item label="上传资源">
                    <el-upload
                        ref="upload"
                        :action="upload()"
                        :multiple="false"
                        :limit="1"
                        :auto-upload="true"
                        accept="image/png,image/jpg,image/jpeg,image/gif,video/mp4"
                        :show-file-list="false"
                        :data="{category: 'album', type: 'media', localFlag: true}"
                        :file-list="fileList"
                        :on-change="handleChange"
                        :on-success="handleSuccess">
                        <el-button size="small" type="success">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">
                            只能上传图片或者视频文件格式。
                            <br/>
                            <media-show v-if="tempUrl" :url="tempUrl" :preview-src-list="tempUrls"></media-show>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addOrUpdateDialogVisible = false" :size="size">取 消</el-button>
                <el-button @click="addOrUpdateConfirm" type="primary" :size="size">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {addAlbum, deleteAlbum, getAlbumByPage, getShopByPage, getUploadUrl, updateAlbum} from '@/api/api'
import {Message} from "element-ui";
import MediaShow from "@/component/single/MediaShow";

export default {
    name: "Album",
    components: {MediaShow},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 18,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            // 相册分类
            category: this.CONST.album_category,

            // 门店数据
            shops: [],
            // 文件列表
            fileList: [],
            // 临时文件url
            tempUrl: '',
            tempUrls: [],
            // 相册url数组
            albumUrls: [],

            colsSize: 6,
            rowsSize: 0,
            rowsData: [],
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        size: {
            type: String,
            default: 'small'
        },
        mode: {
            type: String,
            default: 'list'
        },
        shopId: String,
    },
    methods: {
        upload() {
            return getUploadUrl();
        },
        onSelect: function (row) {
            this.$emit('select', row)
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 文件改变的时候钩子函数
        handleChange(file, fileList) {
            if (!this.addOrUpdateForm.title) {
                this.$set(this.addOrUpdateForm, "title", file.name.substring(0, file.name.lastIndexOf(".")))
            }
        },
        // 文件上传成功后回调
        handleSuccess(response, file, fileList) {
            if (response.respCode != 1000) {
                Message.error('异常码：' + response.respCode + '，异常信息：' + response.respMsg);
                return;
            }
            // 得到上传成功后服务器返回的数据
            this.tempUrl = response.body.url;
            this.tempUrls = [];
            this.tempUrls.push(this.tempUrl);
            // 上传完成后清空文件，以便下次上传
            this.fileList = [];
            this.addOrUpdateForm.url = this.tempUrl;
            this.addOrUpdateForm.size = response.body.size;
            this.addOrUpdateForm.fileLocation = response.body.location;
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatCategory: function (row, column, cellValue) {
            if (!cellValue) {
                return "";
            }
            for (const elem of this.category) {
                if (elem.value == cellValue) {
                    return elem.label;
                }
            }
            return "未知";
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
            if (this.shopId) {
                this.addOrUpdateForm.shopId = this.shopId;
            } else {
                if (this.condition.search.shopId) {
                    this.$set(this.addOrUpdateForm, "shopId", this.condition.search.shopId)
                }
            }
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        add: function () {
            addAlbum(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            updateAlbum(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteAlbum({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取门店列表
        getShops: function () {
            let condition = {
                page: 1,
                rows: 100,
                search: {}
            };
            getShopByPage(condition).then(data => {
                this.shops = data.body.rows;
            });
        },
        // 获取表格数据
        getData: function () {
            if (this.shopId) {
                this.condition.search.shopId = this.shopId;
            }
            getAlbumByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
                this.tableData.forEach((item, index, arr) => {
                    this.albumUrls.push(item.url);
                })

                this.rowsData = [];
                this.rowsSize = Math.ceil(data.body.total / this.colsSize);
                for (let i = 0; i < this.rowsSize; i++) {
                    const temp = [];
                    for (let j = i * this.colsSize; j < this.tableData.length; j++) {
                        if (j < (i + 1) * this.colsSize) {
                            temp.push(this.tableData[j]);
                        } else {
                            break;
                        }
                    }
                    this.rowsData.push({
                        cols: temp
                    })
                }
            });
            this.getShops();
        },
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
